package edu.ynu.se.xiecheng.achitectureclass.demo.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.controller.LogicController;
import edu.ynu.se.xiecheng.achitectureclass.demo.dao.UserDao;
import edu.ynu.se.xiecheng.achitectureclass.demo.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户")
@RestController
@RequestMapping("/api/users")
public class UserController extends LogicController<UserService, UserDao, User, Long> {

    public UserController(@Autowired UserService userService) {
        super(userService);
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public ResponseEntity<?> login(
            @ApiParam(value = "用户名", required = true) @RequestParam String username,
            @ApiParam(value = "密码", required = true) @RequestParam String password
    ) {
        if (getService().isUserExists(username, password)) {
            // 用户存在，生成token
            String token = getService().generateToken(username);
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);
            return ResponseEntity.ok(tokenMap);
        } else {
            // 用户不存在
            return ResponseEntity.badRequest().body("Invalid username or password");
        }
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public ResponseEntity<?> register(
            @ApiParam(value = "用户名", required = true) @RequestParam String username,
            @ApiParam(value = "密码", required = true) @RequestParam String password
    ) {
        // 检查用户名是否已存在
        if (getService().isUsernameExists(username)) {
            return ResponseEntity.badRequest().body("Username already exists");
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setRole("USER");
        // 保存新用户
        getService().POST(newUser);

        Map<String, String> successMap = new HashMap<>();
        successMap.put("success", "success");
        return ResponseEntity.ok(successMap);
    }

}